const router = require('koa-router')()
const cc = require('../conCtl')
const js = require('../jsCtl')
const db = require('../dbCtl')
const pc = require('../projectCtl');

  /**
  @hostpath = http://127.0.0.1:11102/service/users
   */



/** 获取用户列表列表
###
    GET {{hostpath}}?page=1&size=30
### */
router.get('/', async c => {
  let
    page = c.query.page || 1,
    size = c.query.size || 30,
    wRemark = c.query.key || '';

  let model = db.model('t_users');
  if (wRemark)
    model = model.where('`tel` like ?||taobao_id like ?', `%${wRemark}%`, `%${wRemark}%`);

  let data = await model.orderBy('dt_in desc').select(page, size);
  let count = await model.count();

  cc.send_list(c, data, count);
})

/** 更新用户资料
###
    POST {{hostpath}}
    Content-Type: application/json

    {
        "openid":"test_openid",
        "remark":"iiiiii"
    }
### */
router.post('/', async c => {
  js.check_params(
    !c.request.body.openid && '!用户openid')

  let openid = c.request.body.openid;
  let data = {};
  if (c.request.body.tel) data.tel = c.request.body.tel;
  if (c.request.body.lottery_ticket) data.lottery_ticket = c.request.body.lottery_ticket;
  if (c.request.body.remark) data.remark = c.request.body.remark;
  if (c.request.body.taobao_id) data.taobao_id = c.request.body.taobao_id;
  if (c.request.body.points) {
    let addPoints = c.request.body.addPoints * 1;
    data.points = c.request.body.points * 1 + addPoints;
    let log_data = {
      openid,
      direction: addPoints >= 0 ? 0 : 1,
      type: 1,
      pointsValue: addPoints,
      remark: '',
    }
    await db.model('t_points_log').insert(log_data);
  }
  if (Object.keys(data).length > 0)
    await db.model('t_users').where('openid=?', openid).relyUpdate('更新失败', data);

  cc.send(c);
})

module.exports = router